function ChatRoom() {
    this.loadMessageIndexKey = "loadMessageIndex";

    this.init = function () {
        // 先判断用户是否登录了
        let token = getLoginToken();
        if (null == token || "" === token) {
            layer.msg("请登录", {
                time: 1000
            }, function () {
                window.location.href = "../chaos/login.html";
            });
        } else {
            getUserInfo();
            sessionStorage.removeItem(this.loadMessageIndexKey);
            let chatPanel = document.getElementById("chat-panel");
            let that = this;
            chatPanel.onscroll = function () {
                if (this.scrollTop === 0) {
                    console.log("到顶了");
                    that.loadMessage(false);
                }
            }
            this.loadMessage(true);
            this.socketConnect();
        }
    }

    this.socketConnect = function () {
        let that = this;
        // stomp配置信息
        const stompConfig = {
            // brokerURL: "ws://pixelgear.top/chaos/canvas-update-notice-websocket",
            // 域名暂时没有完成备案，先通过IP
            brokerURL: "ws://106.12.181.80/chaos/canvas-update-notice-websocket",
            // brokerURL: "ws://127.0.0.1:9999/chaos/chat-room-websocket",
            debug: function (str) {
                console.log("STOMP: " + str);
            },

            // 断连后200ms自动重连
            reconnectDelay: 200,
            heartbeatIncoming: 4000,
            heartbeatOutgoing: 4000,

            onConnect: function (frame) {
                that.stompClient.subscribe("/topic/chat-message", function (message) {
                    console.log(message);
                    const payload = JSON.parse(message.body);
                    that.handleMessage(payload);
                });
            }
        };

        // 创建客户端实例
        this.stompClient = new StompJs.Client(stompConfig);
        this.stompClient.activate();
    }

    /**
     * 处理消息通知
     * @param notice
     */
    this.handleMessage = function (payload) {

        let userId = payload.userId;
        let nickName = payload.nickName;
        let message = payload.message;
        let dateStr = parseTimestamp(payload.timestamp);
        let messageHtml;
        if (getUserId() === userId) {
            messageHtml =
                '<li class="layui-timeline-item">' +
                '   <i class="layui-icon layui-timeline-axis layui-icon-face-smile-b"></i>' +
                '   <div class="layui-timeline-content layui-text">' +
                '       <h4 class="layui-timeline-title">' + dateStr + '</h4>' +
                '       <p>' +
                '           你: ' + message +
                '       </p>' +
                '   </div>' +
                '</li>';
        } else {
            messageHtml =
                '<li class="layui-timeline-item">' +
                '   <i class="layui-icon layui-timeline-axis layui-icon-circle"></i>' +
                '   <div class="layui-timeline-content layui-text">' +
                '       <h4 class="layui-timeline-title">' + dateStr + '</h4>' +
                '       <p>' +
                '           ' + nickName + ': ' + message +
                '       </p>' +
                '   </div>' +
                '</li>';
        }

        let chatPanel = document.getElementById("chat-panel");
        chatPanel.innerHTML = chatPanel.innerHTML + messageHtml;
        chatPanel.scrollTop = chatPanel.scrollHeight;
    }

    /**
     * 加载历史消息
     * @param addToLast 是否加载到最后
     */
    this.loadMessage = function (addToLast) {
        let paramCache = sessionStorage.getItem(this.loadMessageIndexKey);
        let firstPage, index, size = 10;
        if (null == paramCache || "" === paramCache) {
            // 首次查询
            firstPage = true;
            index = 0;
        } else {
            // 后续查询
            firstPage = false;
            index = parseInt(paramCache);
        }
        if (index === -1) {
            // 已经到达了初始位置，不再查询
            return;
        }
        let that = this;
        let loadMessageUrl = "/chaos/api/chat/messages?firstPage=" + firstPage + "&index=" + index + "&size=" + 10;
        $.ajax({
            method: 'get',
            headers: {
                'token': getLoginToken()
            },
            contentType: "application/json",
            dataType: "json",
            url: loadMessageUrl,
            success: function (res) {
                ensureLogin(res);
                sessionStorage.setItem(that.loadMessageIndexKey, res.body.nextIndex);
                let loginUserId = getUserId();
                let messageData = [];
                for (const messageIndex in res.body.messages) {
                    let messageInfo = res.body.messages[messageIndex];

                    let userId = messageInfo.userId;
                    let nickName = messageInfo.nickName;
                    let message = messageInfo.message;
                    let dateStr = parseTimestamp(messageInfo.timestamp);
                    let messageHtml;
                    if (loginUserId === userId) {
                        messageHtml =
                            '<li class="layui-timeline-item">' +
                            '   <i class="layui-icon layui-timeline-axis layui-icon-face-smile-b"></i>' +
                            '   <div class="layui-timeline-content layui-text">' +
                            '       <h4 class="layui-timeline-title">' + dateStr + '</h4>' +
                            '       <p>' +
                            '           你: ' + message +
                            '       </p>' +
                            '   </div>' +
                            '</li>';
                    } else {
                        messageHtml =
                            '<li class="layui-timeline-item">' +
                            '   <i class="layui-icon layui-timeline-axis layui-icon-circle"></i>' +
                            '   <div class="layui-timeline-content layui-text">' +
                            '       <h4 class="layui-timeline-title">' + dateStr + '</h4>' +
                            '       <p>' +
                            '           ' + nickName + ': ' + message +
                            '       </p>' +
                            '   </div>' +
                            '</li>';
                    }
                    messageData.push(messageHtml);

                }
                let chatPanel = document.getElementById("chat-panel");
                let head = '';
                if (res.body.nextIndex === -1) {
                    head =
                        '<li class="layui-timeline-item">' +
                        '   <i class="layui-icon layui-timeline-axis layui-icon-fire"></i>' +
                        '   <div class="layui-timeline-content layui-text">' +
                        '       <div class="layui-timeline-title">世界起源，再往前就没了</div>' +
                        '   </div>' +
                        '</li>';
                }
                if (addToLast) {
                    chatPanel.innerHTML = chatPanel.innerHTML + messageData.join("");
                    chatPanel.scrollTop = chatPanel.scrollHeight;
                } else {
                    chatPanel.innerHTML = head + messageData.join("") + chatPanel.innerHTML;
                    chatPanel.scrollTop = 10;
                }
            },
            error: function (err) {
                console.log("err");
            }
        });
    }


}

let chatRoom = new ChatRoom();
chatRoom.init();

/**
 * 发送消息
 */
function sendMessage() {
    let textArea = document.getElementById("sendMessageTextArea");
    let messageValue = textArea.value;
    if (null == messageValue || "" === messageValue || messageValue.match(/^\s+$/)) {
        layer.msg("发送的消息不能为空！");
    } else {
        let sendMessageUrl = "/chaos/api/chat/message";
        $.ajax({
            method: 'post',
            headers: {
                'token': getLoginToken()
            },
            contentType: "application/json",
            data: JSON.stringify({
                "message": messageValue
            }),
            dataType: "json",
            url: sendMessageUrl,
            success: function (res) {
                ensureLogin(res);
                textArea.value = "";
                textArea.focus();
            },
            error: function (err) {
                console.log("err");
            }
        });
    }
}

/**
 * 禁用回车，实现发送
 *
 * @param event
 */
function handleChatTextKeyPress(event) {
    if (event.keyCode === 13) {
        event.returnValue = false;
        sendMessage();
    }
}

/**
 * 获取时间格式化字符串 yyyy年MM月dd HH:mm 格式
 * @param timestamp
 * @returns {string}
 */
function parseTimestamp(timestamp) {
    if (0 === timestamp || '0' === timestamp) return '在时间开始之前';
    let date = new Date(timestamp);
    return date.getFullYear() + "年" +
        (date.getMonth() + 1) + "月" +
        date.getDate() + "日 " +
        (date.getHours() + 100 + "").substr(1) +
        ":" +
        (date.getMinutes() + 100 + "").substr(1);
}